<?php


namespace app\plugins\goods\admin\service;


use app\plugins\goods\admin\model\GoodsCates;
use app\plugins\goods\admin\validate\GoodsCatesValidate;
use helper\form\Builder;

/**
 * Class Cates
 * @package app\plugins\goods\admin\service
 * @property Cates $service
 */
class Cates extends \app\admin\service\AdminService
{

    protected function init()
    {
        $this->model = new GoodsCates();
        $this->validate = new GoodsCatesValidate();
    }

    public function getHtml(): string
    {
        $config = [
            [//输入框
                'title' => '分类名称',
                'key' => 'title',
                'value' => '',
                'tips' => '请输入',
                'type' => 'text'
            ],
            [//输入框
                'title' => '分类图标',
                'key' => 'pic',
                'value' => '',
                'type' => 'image',
                'tips' => '分类图标'
            ],
            [//输入框
                'title' => '排序',
                'key' => 'sort',
                'value' => '',
                'tips' => '请输入',
                'type' => 'number'
            ],
            [//输入框
                'title' => '状态',
                'key' => 'status',
                'value' => '',
                'tips' => '请输入',
                'type' => 'switch',
                'option' => '启用|禁用'
            ],
        ];
        return (new Builder($config))->getHtml();
    }

    public function getSelectTree()
    {

        $pid = $this->request->get('pid/d',0);
        if ( !env('app_debug') && cache('?cates')) {
            return cache('cates');
        }

        $list = $this->model->where('status',1)->field('id,title as name,pid')->order('sort asc')->select();
        if($list ){
            $list  = $list->toArray();
        }else{
            return json([]);
        }
        $alist = array_map(function($item)use($pid){
            $item['open'] = true;
            $item['checked'] = $item['id'] == $pid?true:false;
            return $item;
        },$list);
        unset($list);
        $list = recursion($alist);
        $list[-1] = [
            'checked'=> false,
            'id'=> 0,
            'name'=> "顶级分类",
            'open'=> true,
            'pid'=> 0,
        ];
        sort($list);
        return json($list);
    }

}